package com.sitech.portal.system.action;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.opensymphony.xwork2.ActionContext;
import com.sitech.BaseConst;
import com.sitech.context.SpringContext;
import com.sitech.ibnms.core.IPage;
import com.sitech.ibnms.core.JGridBaseAction;
import com.sitech.ibnms.util.DesEncrypterIsmp;
import com.sitech.portal.system.domain.TblSYS_DEPT;
import com.sitech.portal.system.domain.TblSYS_LOGINMSG;
import com.sitech.portal.system.domain.TblSYS_USER_ROLE;
import com.sitech.portal.system.form.UserForm;
import com.sitech.portal.system.service.ISysDeptService;
import com.sitech.portal.system.service.ISysLogInmsgService;
import com.sitech.portal.system.service.ISysLogUserChangeService;
import com.sitech.portal.system.service.ISysParaService;
import com.sitech.portal.system.service.ISysRoleDeptService;
import com.sitech.portal.system.service.ISysRoleService;
import com.sitech.portal.system.service.ISysStyleService;
import com.sitech.portal.system.service.ISysUserRoleService;
import com.sitech.portal.system.service.ISysWorkGroupDeptService;
import com.sitech.portal.system.service.ISysWorkGroupService;
import org.apache.commons.lang.StringUtils;

public class UserAction extends JGridBaseAction{
	
	private UserForm userForm = new UserForm();
	private TblSYS_DEPT dept;
	private ISysLogInmsgService sysLogInmsgService;
	private ISysRoleService sysRoleService;
	private ISysDeptService sysDeptService;
	private ISysUserRoleService sysUserRoleService;
	private ISysWorkGroupService sysWorkGroupService;
	private ISysRoleDeptService sysRoleDeptService;
	private ISysLogUserChangeService sysLogUserChangeService;
	private ISysWorkGroupDeptService sysWorkGroupDeptService;
	private List canRoleList;
	private List roleList;
	private List deptlist;
	private List workGroupList;
	private String flag;
	private Map mapJson;

	public ISysWorkGroupDeptService getSysWorkGroupDeptService() {
		return sysWorkGroupDeptService;
	}
	public void setSysWorkGroupDeptService(
			ISysWorkGroupDeptService sysWorkGroupDeptService) {
		this.sysWorkGroupDeptService = sysWorkGroupDeptService;
	}
	public ISysLogUserChangeService getSysLogUserChangeService() {
		return sysLogUserChangeService;
	}
	public void setSysLogUserChangeService(
			ISysLogUserChangeService sysLogUserChangeService) {
		this.sysLogUserChangeService = sysLogUserChangeService;
	}
	public ISysRoleDeptService getSysRoleDeptService() {
		return sysRoleDeptService;
	}
	public void setSysRoleDeptService(ISysRoleDeptService sysRoleDeptService) {
		this.sysRoleDeptService = sysRoleDeptService;
	}
	public ISysUserRoleService getSysUserRoleService() {
		return sysUserRoleService;
	}
	public void setSysUserRoleService(ISysUserRoleService sysUserRoleService) {
		this.sysUserRoleService = sysUserRoleService;
	}
	
	public ISysWorkGroupService getSysWorkGroupService() {
		return sysWorkGroupService;
	}
	public void setSysWorkGroupService(ISysWorkGroupService sysWorkGroupService) {
		this.sysWorkGroupService = sysWorkGroupService;
	}
	
	public List getWorkGroupList() {
		return workGroupList;
	}
	public void setWorkGroupList(List workGroupList) {
		this.workGroupList = workGroupList;
	}
	public String getFlag() {
		return flag;
	}
	public void setFlag(String flag) {
		this.flag = flag;
	}
	public TblSYS_DEPT getDept() {
		return dept;
	}
	public void setDept(TblSYS_DEPT dept) {
		this.dept = dept;
	}
	public ISysDeptService getSysDeptService() {
		return sysDeptService;
	}
	public void setSysDeptService(ISysDeptService sysDeptService) {
		this.sysDeptService = sysDeptService;
	}
	public ISysRoleService getSysRoleService() {
		return sysRoleService;
	}
	public void setSysRoleService(ISysRoleService sysRoleService) {
		this.sysRoleService = sysRoleService;
	}
	public List getCanRoleList() {
		return canRoleList;
	}
	public void setCanRoleList(List canRoleList) {
		this.canRoleList = canRoleList;
	}
	public List getRoleList() {
		return roleList;
	}
	public void setRoleList(List roleList) {
		this.roleList = roleList;
	}
	public List getDeptlist() {
		return deptlist;
	}
	public void setDeptlist(List deptlist) {
		this.deptlist = deptlist;
	}
	public UserForm getUserForm() {
		return userForm;
	}
	public void setUserForm(UserForm userForm) {
		this.userForm = userForm;
	}
	public ISysLogInmsgService getSysLogInmsgService() {
		return sysLogInmsgService;
	}
	public void setSysLogInmsgService(ISysLogInmsgService sysLogInmsgService) {
		this.sysLogInmsgService = sysLogInmsgService;
	}
	/**
	 * 显示用户列表
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws BaseException
	 */
	public String loadListUser() {
		String type = this.getRequest().getParameter("type");
		if ("changeLoginUser".equals(type)){
			return type;
		}else if("select".equals(type)){
			return "SELECT";
		}else {
			return SUCCESS;
		}
	}
	public String loadListUserQueryJson() {
		String deptId = userForm.getDEPT_ID();
		String login_id = userForm.getUserId();
		String userName = userForm.getUserName();
		String loginPhone = userForm.getTelphone();

		IPage result = sysLogInmsgService.findListByDeparyTypeAndUnit(login_id, userName, loginPhone, deptId,this.getPageForm());
		this.setResult(result);

		return SUCCESS;
	}
	
	public String loadUserManage(){
        Boolean isAdmin =   sysRoleService.isAdmin(this.getCurrentUser().getLOGIN_ID());
        if(isAdmin){
            userForm.setOrgName("部门树");
            userForm.setDEPT_ID("0");
        }else{
            List<HashMap> list = sysDeptService.findDeptByMgrId(this.getCurrentUser().getLOGIN_ID());
            if(list!=null&&list.size()>0&&!isAdmin){
                HashMap map = list.get(0);
                userForm.setOrgName(map.get("DEPT_NAME").toString());
                userForm.setDEPT_ID(map.get("DEPT_ID").toString());
            }else{
                userForm.setOrgName("部门树");
                userForm.setDEPT_ID("0");
            }
        }
		//判断参数跳转到切换用户界面
		String type = getRequest().getParameter("type");
		if ("changeLoginUser".equals(type)){
			getRequest().setAttribute("changeLoginUser",type);
			return type;
		}
		return SUCCESS;
	}
	
	/**
	 * 进入用户编辑
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws BaseException
	 */
	public String editUserInfo() {

		String userId = userForm.getLOGIN_ID();
        Boolean isAdmin =   sysRoleService.isAdmin(this.getCurrentUser().getLOGIN_ID());
        if(isAdmin){
            roleList = sysRoleService.findForListToAll();
            workGroupList = sysWorkGroupService.findAllWorkGroup();
        }else{
            List<HashMap> deptList = this.getCurrentUser().getMgrDepts();
            if(deptList!=null&&deptList.size()>0){//是管理员，查找能分配的角色和岗位列表
                roleList = sysRoleDeptService.findRoleDeptListByUser(this.getCurrentUser().getLOGIN_ID());
                workGroupList = sysWorkGroupDeptService.findWorkGroupDeptListByUser(this.getCurrentUser().getLOGIN_ID());
            }else{
                roleList = sysRoleService.findForListToAll();
                workGroupList = sysWorkGroupService.findAllWorkGroup();
            }
        }

		
		dept = sysDeptService.findDepartByPK(userForm.getDEPT_ID());
		
		String type = this.getRequest().getParameter("type");
		if (type != null && type.equals("add")) {
			return SUCCESS;
		}
		
		if (userId != null) {

			TblSYS_LOGINMSG user = sysLogInmsgService.findUserRoleByPk(userId);
			if (user != null) {
				List list = user.getRoles();
				String roleIds = "";
				for(int i=0;i<list.size();i++){
					HashMap role = (HashMap)list.get(i);
					roleIds += role.get("ROLE_ID") + ",";
				}
				user.setRoleIds(roleIds);
				
				List workgroups = user.getWorkGroups();
				String workgroupIds = "";
				for(int i=0;i<workgroups.size();i++){
					HashMap workgroup = (HashMap)workgroups.get(i);
					workgroupIds += workgroup.get("WORKGROUP_ID") + ",";
				}
				user.setWorkGroupIds(workgroupIds);
				
				userForm = new UserForm(user);
				
				try{
					DesEncrypterIsmp encrypter = new DesEncrypterIsmp();
					userForm.setPassword(encrypter.decrypt(user.getLOGIN_PASSWD()));
				}catch(Exception e){
					e.printStackTrace();
				}
			}
		}

		return SUCCESS;
	}
	
	/**
	 * 保存
	 * 
	 * @param 	mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws BaseException
	 */
	public String saveUser() {

		flag = "true";
		
		String[] ROLE_ID = this.getRequest().getParameterValues("multiselect_0");
		if(ROLE_ID==null)
			ROLE_ID = userForm.getAlreadySelect();
		
		String[] workGroupIds = this.getRequest().getParameterValues("multiselect_1");
		if(workGroupIds==null)
			workGroupIds = userForm.getWorkGroupSelect();
		
		String cmd = userForm.getAction_type();
		TblSYS_LOGINMSG user = sysLogInmsgService.findByUserCode(userForm.getLOGIN_ID());
		
		if(cmd.equals("add")&&user!=null){
			flag = "该用户id已经使用，不能添加";
			return SUCCESS;
		}
		
		try{
			if(user==null)
				user = new TblSYS_LOGINMSG();
			
			DesEncrypterIsmp encrypter = new DesEncrypterIsmp();
			
			user.setLOGIN_ID(userForm.getLOGIN_ID());
			user.setNAME(userForm.getUserName());
			user.setLOGIN_PASSWD(encrypter.encrypt(userForm.getPassword()));
			user.setEMAIL_ADDR(userForm.getEmail());
			user.setLOGIN_PHONE(userForm.getTelphone());
			user.setDEPT_ID(userForm.getDEPT_ID());
			user.setCOMP_ID(userForm.getCOMP_ID());
			user.setLOCAL_PHONE(userForm.getLocal_phone());
			user.setUSER_ID_UP(userForm.getUserId());
			user.setLOCKSTATE(userForm.getLockState());
			user.setIS_VIP(userForm.getIS_VIP());
			
			if(cmd.equals("add")){
				sysLogInmsgService.add(user);
			}else{
				sysLogInmsgService.update(user);
			}
			
			sysUserRoleService.add(user, ROLE_ID, user);
			sysWorkGroupService.insertUserToWorkGroup(user.getLOGIN_ID(), workGroupIds);
		}catch(Exception e){
			e.printStackTrace();
			flag = "保存失败："+e.getMessage();
			return SUCCESS;
		}
		
		return SUCCESS;
	}
	
	/**
	 * 删除用户
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws BaseException
	 */
	public String delUser() {

		flag = "true";
		String[] loginIDs = userForm.getLOGIN_ID().split(",");

		try {
			sysLogInmsgService.delete(loginIDs);
			sysUserRoleService.deleteByUserId(loginIDs);
		} catch (Exception e) {
			flag = e.getMessage();
		}
		return SUCCESS;
	}
	
	
	/**
	 * 显示已冻结的用户列表
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws BaseException
	 */
	public String frozenList() {
		return SUCCESS;
	}
	
	public String unfrozenListQueryJson() {

		try{
			HashMap map = new HashMap();
			map.put("USER_ID", userForm.getUserId());
			map.put("USER_NAME", userForm.getUserName());
			if(this.getCurrentUser().getMgrDepts()!=null && this.getCurrentUser().getMgrDepts().size()>0){//部门管理员
				map.put("MGR_ID", this.getCurrentUser().getLOGIN_ID());
			}
			
			IPage result = sysLogInmsgService.findUnfrozenList(map,this.getPageForm());

			this.setResult(result);
		}catch(Exception e){
			e.printStackTrace();
		}

		return SUCCESS;

	}
	
	public String frozenListQueryJson() {
		try{
			HashMap map = new HashMap();
			map.put("USER_ID", userForm.getUserId());
			map.put("USER_NAME", userForm.getUserName());
			if(this.getCurrentUser().getMgrDepts()!=null && this.getCurrentUser().getMgrDepts().size()>0){//部门管理员
				map.put("MGR_ID", this.getCurrentUser().getLOGIN_ID());
			}
			IPage result = sysLogInmsgService.findFrozenList(map,this.getPageForm());
			this.setResult(result);
		}catch(Exception e ){
			e.printStackTrace();
		}
		return SUCCESS;
	}
	
	/**
	 * 冻结用户操作
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws BaseException
	 */
	public String frozenUser() {

		flag = "true";
		String[] loginIDs = userForm.getLOGIN_ID().split(",");

		try {
			sysLogInmsgService.frozenUser(loginIDs);
		} catch (Exception e) {
			flag = e.getMessage();
		}
		return SUCCESS;
	}
	
	/**
	 * 取消冻结操作
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws BaseException
	 */
	public String cancelfrozenUser() {
		flag = "true";
		String[] loginIDs = userForm.getLOGIN_ID().split(",");

		try {
			sysLogInmsgService.cancelfrozen(loginIDs);
		} catch (Exception e) {
			flag = e.getMessage();
		}
		return SUCCESS;
	}
	
	
	public String changeUser(){
		flag = "true";
		String userId = this.getRequest().getParameter("loginId");

		try {
			TblSYS_LOGINMSG user = sysLogInmsgService.findByUserCode(userId);
			// 获得用户的界面风格设置信息
			ISysStyleService sysStyleService = (ISysStyleService) SpringContext.getBean("sysStyleService");
			ISysParaService sysParaService = (ISysParaService) SpringContext.getBean("sysParaService");
			String DEFAULT_STYLE_PATH = sysParaService.findSysParaByParaId(
					"STYLE_PATH").get("PARA_VALUE").toString();
			String stylePath = sysStyleService.getSYSStylePath(null);
			if (stylePath == null || "".equals(stylePath)
					|| "null".equals(stylePath)) {
				stylePath = DEFAULT_STYLE_PATH;
			}

			String STYLE_IS_TAB = sysStyleService.getIsTab(null);
			if (STYLE_IS_TAB == null || "".equals(STYLE_IS_TAB)
					|| "null".equals(STYLE_IS_TAB)) {
				STYLE_IS_TAB = "0";
			}
			user.setSTYLE_IS_TAB(STYLE_IS_TAB);
			user.setStylePath(stylePath);
			
            // 用户拥有的角色
			ISysRoleService sysRoleService = (ISysRoleService) SpringContext.getBean("sysRoleService");
            TblSYS_USER_ROLE rol = new TblSYS_USER_ROLE();
            rol.setLOGIN_ID(user.getLOGIN_ID());
            user.setRoles(sysRoleService.findForRoleListByLonginId(rol));
            
            sysLogUserChangeService.addUserChangeDao(this.getCurrentUser().LOGIN_ID, userId);
            
            HttpServletRequest httpRequest = (HttpServletRequest) this.getRequest();
            httpRequest.getSession().setAttribute(System.getProperty(BaseConst.SSO_USER_SESSION_PATH),userId);
            httpRequest.getSession().setAttribute(BaseConst.SESSION_USER_KEY, user);
            
		} catch (Exception e) {
			e.printStackTrace();
			flag = e.getMessage();
		}
		return SUCCESS;
	}

	public String findUserInfoByLoginId() {
		mapJson = sysLogInmsgService.findUserinfo(userForm.getLOGIN_ID());
		return SUCCESS;
	}

	public Map getMapJson() {
		return mapJson;
	}

	public void setMapJson(Map mapJson) {
		this.mapJson = mapJson;
	}
}
